import React from 'react';
import { Form, Input, InputNumber, Radio, Button, Modal, message, Row, Col, Upload, Spin, AutoComplete, Tooltip } from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = AutoComplete.Option;
import * as actions from './../../../actions/backstage/loginAction';

class personalInfo extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            visiblePersonal: false,
            visibleAlert: false,
            updateLoading: false,
            modifyLoading: false,

            serverData: {},
            fieldsValue: {},
            result: []
        }
    }
    componentDidMount() {
        actions.findProfileById(this);
    }
    // 提交表单
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
          if (!err) {
            this.setState({
              visibleAlert: true,
              fieldsValue: values
            });
          }
        });
    }
    onCancelAlert() {
        this.setState({ visibleAlert: false })
    }
    onEditPersonal(){
        this.setState({ visiblePersonal: true })
    }
    onConfirmModify(){
        if(this.state.serverData.id != undefined){
            this.setState({ modifyLoading: true, visibleAlert: false });
            this.state.serverData.firstName = ((this.state.fieldsValue.firstName == undefined)?"":this.state.fieldsValue.firstName)
            this.state.serverData.lastName = ((this.state.fieldsValue.lastName == undefined)?"":this.state.fieldsValue.lastName)
            this.state.serverData.location = ((this.state.fieldsValue.location == undefined)?"":this.state.fieldsValue.location)
            this.state.serverData.overview = ((this.state.fieldsValue.overview == undefined)?"":this.state.fieldsValue.overview)
            this.state.serverData.job = ((this.state.fieldsValue.job == undefined)?"":this.state.fieldsValue.job)
            this.state.serverData.position = ((this.state.fieldsValue.position == undefined)?"":this.state.fieldsValue.position)
            this.state.serverData.age = ((this.state.fieldsValue.age == undefined)?"":this.state.fieldsValue.age)
            this.state.serverData.gender = ((this.state.fieldsValue.gender == undefined)?"":this.state.fieldsValue.gender)
            this.state.serverData.phoneNum = ((this.state.fieldsValue.phoneNum == undefined)?"":this.state.fieldsValue.phoneNum)
            this.state.serverData.email = ((this.state.fieldsValue.email == undefined)?"":this.state.fieldsValue.email)

            actions.updateProfile(this, this.state.serverData);
        }else{
            message.warning('Personal information initialization error.');
        }
    }
    beforeUpload(file) {
      if (!(file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp')) {
        message.warning('您只能上传 JPG、PNG、GIF 和 BMP 文件！');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.warning('照片必须小于 2MB!');
        return false;
      }
      this.setState({updateLoading: true});
      return true;
    }
    handleChange (info){
      if (info.file.status === 'done') {
          debugger;
          this.state.serverData.photoPic = info.file.response.data.photoPic;
          this.setState({
            serverData: this.state.serverData
          });
      }
    }
    onImgLoaded(){
      this.setState({updateLoading: false});
    }
    showCommonMailbox(value){
      let result;
      if (!value || value.indexOf('@') >= 0) {
        result = [];
      } else {
        result = ['hotmail.com', 'gmail.com', 'sina.com', '163.com', '126.com', 'qq.com'].map(domain => `${value}@${domain}`);
      }
      this.setState({ result });
    }
    render() {
        var photoPic = null;
        const { getFieldDecorator } = this.props.form
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 16 }
        }
        if(this.state.serverData.photoPic != undefined){
            // photoPic = <Upload
            //   name="uPhoto"
            //   showUploadList={false}
            //   headers={{userAuth: sessionStorage.getItem('staffAuth')}}
            //   action={window.GLOBAL.baseURL + "/webAPI/settings/updateUserPortrait"}
            //   beforeUpload={this.beforeUpload.bind(this)}
            //   onChange={this.handleChange.bind(this)}
            // >
            //   <img src={this.state.serverData.photoPic} title="头像" onLoad={this.onImgLoaded.bind(this)}/>
            // </Upload>
            photoPic = <img src={this.state.serverData.photoPic} title="头像" onLoad={this.onImgLoaded.bind(this)}/>
        }else{
            // photoPic = <Upload
            //   name="uPhoto"
            //   showUploadList={false}
            //   headers={{userAuth: sessionStorage.getItem('staffAuth')}}
            //   action={window.GLOBAL.baseURL + "/webAPI/settings/updateUserPortrait"}
            //   beforeUpload={this.beforeUpload.bind(this)}
            //   onChange={this.handleChange.bind(this)}
            // >
            //   <img src='/src/styles/images/default.png' title="头像"/>
            // </Upload>
            photoPic = <img src='/src/styles/images/default.png' style={{cursor: 'initial'}} title="头像"/>
        }
        const { result } = this.state;
        const children = result.map((email) => {
          return <Option key={email}>{email}</Option>;
        });
        return (
          <div className="divPersonalInfo">
                <div className="divContent">
                    <div className="divTitle">
                      个人信息
                      <Button type="primary" icon="edit" className="btnEdit" onClick={this.onEditPersonal.bind(this)}>修改信息</Button>
                    </div>
                    <Spin spinning={this.state.updateLoading} tip="图片上传中...">
                      <table cellSpacing="1" cellPadding="0">
                        <tbody>
                          <tr>
                            <td rowSpan="5" className="tdImage" style={{verticalAlign: 'top'}}>
                              {photoPic}
                            </td>
                            <td className="tdTitle">姓名：</td>
                            <td className="tdValue">
                              {((this.state.serverData.firstName == undefined)?"":this.state.serverData.firstName) +" "+ ((this.state.serverData.lastName==undefined)?"":this.state.serverData.lastName)}
                            </td>
                            <td className="tdTitle">性别：</td>
                            <td className="tdValue">{(this.state.serverData.gender == 1)?"男":"女"}</td>
                          </tr>
                          <tr>
                            <td className="tdTitle">年龄：</td>
                            <td className="tdValue">{this.state.serverData.age}</td>
                            <td className="tdTitle">电话：</td>
                            <td className="tdValue">{this.state.serverData.phoneNum}</td>
                          </tr>
                          <tr>
                            <td className="tdTitle">电子邮件：</td>
                            <td className="tdValue">{this.state.serverData.email}</td>
                            <td className="tdTitle">工作：</td>
                            <td className="tdValue">{this.state.serverData.job}</td>
                          </tr>
                          <tr>
                            <td className="tdTitle">位置：</td>
                            <td className="tdValue" colSpan="3">
                              <div className="divRoles">
                                <Tooltip placement="bottomLeft" title={((this.state.serverData.location == undefined)?"":this.state.serverData.location) +" "+ ((this.state.serverData.position == undefined)?"":this.state.serverData.position)}>
                                  {((this.state.serverData.location == undefined)?"":this.state.serverData.location) +" "+ ((this.state.serverData.position == undefined)?"":this.state.serverData.position)}
                                </Tooltip>
                              </div>
                            </td>
                          </tr>
                          <tr>
                            <td className="tdTitleArea">个人简介：</td>
                            <td colSpan="3" className="tdTextArea">{this.state.serverData.overview}</td>
                          </tr>
                        </tbody>
                      </table>
                    </Spin>
                </div>
                <Modal
                  visible={this.state.visiblePersonal}
                  title="修改用户信息"
                  footer={null}
                  wrapClassName="vertical-center-modal"
                  onCancel={()=>{this.setState({visiblePersonal: false})}}
                >
                  <Spin spinning={this.state.modifyLoading} tip="修改中，请稍候...">
                    <Form onSubmit={this.handleSubmit.bind(this)} style={{width: '100%'}}>
                        <FormItem
                            label="姓氏"
                            {...formItemLayout}>
                            <Row gutter={8}>
                                <Col span={12}>
                                  {getFieldDecorator('firstName', {
                                    rules: [{ required: true, message: '姓氏 不能为空。' }],
                                    initialValue: this.state.serverData.firstName
                                  })(<Input placeholder="请输入姓氏..." type="text"/>)}
                                </Col>
                                <Col span={12}>
                                  {getFieldDecorator('lastName', {
                                    rules: [{ required: true, message: '' }],
                                    initialValue: this.state.serverData.lastName
                                  })(<Input placeholder="请输入名字..." type="text"/>)}
                                </Col>
                            </Row>
                        </FormItem>
                        <FormItem
                            label="性别"
                            {...formItemLayout}>
                            {getFieldDecorator('gender', {
                              rules: [{ required: true, message: '性别 不能为空。' }],
                              initialValue: this.state.serverData.gender
                            })(
                              <Radio.Group>
                                <Radio value="1">男</Radio>
                                <Radio value="2">女</Radio>
                              </Radio.Group>
                            )}
                        </FormItem>
                        <FormItem
                            label="年龄"
                            {...formItemLayout}>
                            {getFieldDecorator('age', {
                              rules: [{ required: true, message: '年龄 不能为空。' }],
                              initialValue: this.state.serverData.age
                            })(
                              <InputNumber min={1} max={100} />
                            )}
                        </FormItem>
                        <FormItem
                            label="电话 / 邮箱"
                            {...formItemLayout}>
                            <Row gutter={8}>
                                <Col span={12}>
                                  {getFieldDecorator('phoneNum', {
                                    rules: [{ required: false }],
                                    initialValue: this.state.serverData.phoneNum
                                  })(<Input placeholder="请输入电话..." type="text"/>)}
                                </Col>
                                <Col span={12}>
                                  {getFieldDecorator('email', {
                                    rules: [{ required: false}],
                                    initialValue: this.state.serverData.email
                                  })(<AutoComplete
                                      onSearch={this.showCommonMailbox.bind(this)}
                                      placeholder="请输入邮箱..."
                                      disabled={true}
                                    >
                                      {children}
                                    </AutoComplete>
                                  )}
                                </Col>
                            </Row>
                        </FormItem>
                        <FormItem
                            label="位置"
                            {...formItemLayout}>
                            <Row gutter={8}>
                                <Col span={12}>
                                {getFieldDecorator('location', {
                                  rules: [{ required: false}],
                                  initialValue: this.state.serverData.location
                                })(<Input placeholder="请输入 省份/市/区..." />)}
                                </Col>
                                <Col span={12}>
                                {getFieldDecorator('position', {
                                  rules: [{ required: false}],
                                  initialValue: this.state.serverData.position
                                })(<Input placeholder="请输入 街道/号数..." />)}
                                </Col>
                            </Row>
                        </FormItem>
                        <FormItem
                            label="工作"
                            {...formItemLayout}>
                            {getFieldDecorator('job', {
                              rules: [{ required: false}],
                              initialValue: this.state.serverData.job
                            })(
                              <Input placeholder="请输入工作..." />
                            )}
                        </FormItem>
                        <FormItem
                            label="个人简介"
                            {...formItemLayout}>
                            {getFieldDecorator('overview', {
                              rules: [{ required: false}],
                              initialValue: this.state.serverData.overview
                            })(
                              <Input placeholder="请输入个人简介..." type="textarea" rows={4}/>
                            )}
                        </FormItem>

                        <FormItem wrapperCol={{ span: 21, offset: 0 }} style={{ marginTop: 24,textAlign: 'center' }}>
                            <Button className="btnPersonalClose" icon="close" onClick={()=>{this.setState({visiblePersonal: false})}}>取 消</Button>
                            <Button type="primary" htmlType="submit" icon="edit">修改信息</Button>
                        </FormItem>
                    </Form>
                  </Spin>
                </Modal>

                <Modal title="提示" wrapClassName="vertical-center-modal" visible={this.state.visibleAlert} onOk={this.onConfirmModify.bind(this)} onCancel={this.onCancelAlert.bind(this)}>
                    你确定要修改个人信息吗?
                </Modal>
            </div>
        )
    }
}

personalInfo = Form.create()(personalInfo)
export default personalInfo;
